package org.backend.canteenbackend.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.backend.canteenbackend.entity.*;
import org.backend.canteenbackend.persistence.*;
import org.backend.canteenbackend.service.OrderService;
import org.backend.canteenbackend.vo.LineItemVO;
import org.backend.canteenbackend.vo.OrderStatusVO;
import org.backend.canteenbackend.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private LineItemMapper lineItemMapper;


    //通过orderId来删除订单
    @Override
    public boolean deleteOrderByOrderid(int orderid) {
        try {
            QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderStatusQueryWrapper.eq("orderid", orderid);
            orderQueryWrapper.eq("orderid", orderid);
            orderStatusMapper.delete(orderStatusQueryWrapper);
            orderMapper.delete(orderQueryWrapper);
            orderStatusMapper.deleteById(orderid);
            lineItemMapper.deleteById(orderid);
            return true;
        }catch (Exception e) {
            return false;
        }
    }

    //通过orderId来删除订单状态
    @Override
    public void deleteOrderStatusByOrderId(int orderId) {
        orderStatusMapper.deleteById(orderId);
    }

    //通过orderId来删除订单的商品信息
    @Override
    public void deleteLineItemByOrderId(int orderId) {
        lineItemMapper.deleteById(orderId);
    }

    @Override
    public List<Order> findAllOrders() {
        return orderMapper.selectList(null);
    }

    @Override
    public Order findOrderByOrderid(int orderid) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("orderid",orderid);
        return orderMapper.selectOne(orderQueryWrapper);
    }

    @Override
    public List<Order> findOrderByUserid(String userid) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("userid",userid);
        return orderMapper.selectList(orderQueryWrapper);
    }

    @Override
    public List<OrderStatus> findAllOrderStatus() {
        return orderStatusMapper.selectList(null);
    }

    @Override
    public List<LineItem> findLineItemsByOrderId(int orderId) {
        //点击详情按钮后，通过orderId来寻找订单的商品购买信息
        QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
        lineItemQueryWrapper.eq("orderid",orderId);// 根据orderId查询订单的商品项
        List<LineItem> lineItemList = lineItemMapper.selectList(lineItemQueryWrapper);// 获取符合条件的商品项列表
        for (LineItem lineItem:lineItemList){
            String itemId = lineItem.getItemId(); // 获取当前商品项的itemId
            QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("itemid",itemId);// 根据itemId查询商品详细信息
            Item item = itemMapper.selectOne(itemQueryWrapper);// 获取该商品的详细信息

            String productId = item.getProductId();// 获取该商品对应的productId
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("productid",productId); // 根据productId查询产品信息
            Product product = productMapper.selectOne(productQueryWrapper);

            String categoryId = product.getCategoryId(); // 获取产品所属的分类ID
            lineItem.setProductId(productId); // 将productId设置到lineItem中
            lineItem.setCategoryId(categoryId); // 将categoryId设置到lineItem中
        }
        return lineItemList; // 返回包含完整信息的商品项列表
    }

    @Override
    public void updateOrderByOrderid(Order order) {
        orderMapper.updateById(order);
    }

    @Override
    public void updateStatusByOrderid(int orderid, String status) {
        QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
        orderStatusQueryWrapper.eq("orderid",orderid);
        OrderStatus orderStatus = orderStatusMapper.selectOne(orderStatusQueryWrapper);
        orderStatus.setStatus(status);
        orderStatusMapper.updateById(orderStatus);
    }

    @Override
    public void updateInventoryByLineItem(List<LineItem> lineItemList) {
        if (lineItemList == null || lineItemList.isEmpty()) {
            throw new IllegalArgumentException("商品项列表不能为空！");
        }

        for (LineItem lineItem : lineItemList) {
            String itemId = lineItem.getItemId(); // 获取商品 ID
            int quantity = lineItem.getQuantity(); // 获取商品数量

            // 查询当前库存
            QueryWrapper<Inventory> inventoryQueryWrapper = new QueryWrapper<>();
            inventoryQueryWrapper.eq("itemid", itemId);
            Inventory inventory = inventoryMapper.selectOne(inventoryQueryWrapper);

            if (inventory != null) {
                // 减少库存数量
                int newQty = inventory.getQuantity() - quantity;
                if (newQty >= 0) {
                    inventory.setQuantity(newQty);
                    // 更新库存
                    inventoryMapper.updateById(inventory);
                    System.out.println("商品 " + itemId + " 库存更新为：" + newQty);
                } else {
                    System.out.println("商品 " + itemId + " 库存不足，无法更新！");
                    throw new RuntimeException("商品 " + itemId + " 库存不足，无法更新！");
                }
            } else {
                System.out.println("商品 " + itemId + " 库存记录不存在！");
                throw new RuntimeException("商品 " + itemId + " 库存记录不存在！");
            }
        }
    }

    @Override
    public boolean checkStockByOrderId(int orderId) {
        // 获取订单的商品项
        List<LineItem> lineItemList = findLineItemsByOrderId(orderId);

        // 检查每个商品的库存是否充足
        for (LineItem lineItem : lineItemList) {
            String itemId = lineItem.getItemId();
            int quantity = lineItem.getQuantity();

            // 查询当前库存
            QueryWrapper<Inventory> inventoryQueryWrapper = new QueryWrapper<>();
            inventoryQueryWrapper.eq("itemid", itemId);
            Inventory inventory = inventoryMapper.selectOne(inventoryQueryWrapper);

            if (inventory == null || inventory.getQuantity() < quantity) {
                // 库存不足
                return false;
            }
        }

        // 所有商品库存充足
        return true;
    }

    public List<OrderVO> findOrderVOs(){
        //寻找所有订单，放入orderList信息
        List<Order> orderList = orderMapper.selectList(null);
        //寻找所有订单状态，放入orderStatusList
        List<OrderStatus> orderStatusList = orderStatusMapper.selectList(null);

        // 创建OrderVO列表
        List<OrderVO> orderVOList = new ArrayList<>();
        // 将订单和状态合并转换
        for (Order order : orderList) {
            OrderVO orderVO = orderToOrderVO(order, orderStatusList);
            if (orderVO.getOrderStatus() != null) {  // 只添加有状态的订单
                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }

    private OrderVO orderToOrderVO(Order order, List<OrderStatus> allStatuses) {
        OrderVO orderVO = new OrderVO();
        // 1. 设置订单基本信息
        orderVO.setOrderId(order.getOrderId());
        orderVO.setUsername(order.getUsername());
        orderVO.setOrderDate(order.getOrderDate());
        orderVO.setTotalPrice(order.getTotalPrice());
        orderVO.setLocale(order.getLocale());

        // 2. 设置收货地址信息
        orderVO.setShipToFirstName(order.getShipToFirstName());
        orderVO.setShipToLastName(order.getShipToLastName());
        orderVO.setShipAddress1(order.getShipAddress1());
        orderVO.setShipAddress2(order.getShipAddress2());
        orderVO.setShipCity(order.getShipCity());
        orderVO.setShipState(order.getShipState());
        orderVO.setShipZip(order.getShipZip());
        orderVO.setShipCountry(order.getShipCountry());

        // 3. 设置账单信息
        orderVO.setBillToFirstName(order.getBillToFirstName());
        orderVO.setBillToLastName(order.getBillToLastName());
        orderVO.setBillAddress1(order.getBillAddress1());
        orderVO.setBillAddress2(order.getBillAddress2());
        orderVO.setBillCity(order.getBillCity());
        orderVO.setBillState(order.getBillState());
        orderVO.setBillZip(order.getBillZip());
        orderVO.setBillCountry(order.getBillCountry());

        // 4. 设置支付信息
        orderVO.setCreditCard(order.getCreditCard());
        orderVO.setCardType(order.getCardType());
        orderVO.setExpiryDate(order.getExpiryDate());

        // 5. 设置物流信息
        orderVO.setCourier(order.getCourier());

        for (OrderStatus status : allStatuses) {
            if (order.getOrderId() == status.getOrderid()) {
                OrderStatusVO statusVO = new OrderStatusVO();
                statusVO.setOrderid(status.getOrderid());
                statusVO.setLinenum(status.getLinenum());
                statusVO.setTimestamp(status.getTimestamp());
                statusVO.setStatus(status.getStatus());
                orderVO.setOrderStatus(statusVO);
                break; // 找到第一个匹配的状态后即停止
            }
        }
        return orderVO;
    }


    @Override
    public List<LineItemVO> findLineItemVOsByOrderId(int orderId) {
        //点击详情按钮后，通过orderId来寻找订单的商品购买信息
        QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
        lineItemQueryWrapper.eq("orderid",orderId);// 根据orderId查询订单的商品项
        List<LineItem> lineItemList = lineItemMapper.selectList(lineItemQueryWrapper);// 获取符合条件的商品项列表
        for (LineItem lineItem:lineItemList){
            String itemId = lineItem.getItemId(); // 获取当前商品项的itemId
            QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("itemid",itemId);// 根据itemId查询商品详细信息
            Item item = itemMapper.selectOne(itemQueryWrapper);// 获取该商品的详细信息

            String productId = item.getProductId();// 获取该商品对应的productId
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("productid",productId); // 根据productId查询产品信息
            Product product = productMapper.selectOne(productQueryWrapper);

            String categoryId = product.getCategoryId(); // 获取产品所属的分类ID
            lineItem.setProductId(productId); // 将productId设置到lineItem中
            lineItem.setCategoryId(categoryId); // 将categoryId设置到lineItem中
        }

        // 转换为VO列表
        List<LineItemVO> voList = new ArrayList<>();
        for (LineItem lineItem : lineItemList) {
            LineItemVO vo = new LineItemVO();
            vo.setOrderId(lineItem.getOrderId());
            vo.setLineNumber(lineItem.getLineNumber());
            vo.setQuantity(lineItem.getQuantity());
            vo.setItemId(lineItem.getItemId());
            vo.setUnitPrice(lineItem.getUnitPrice());
            vo.setProductId(lineItem.getProductId());
            vo.setCategoryId(lineItem.getCategoryId());

            voList.add(vo);
        }
        return voList;
    }

    @Override
    public OrderVO findOrderVOByOrderId(int orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return null;
        }

        List<OrderStatus> statusList = orderStatusMapper.selectList(null);

        return orderToOrderVO(order, statusList);
    }

    @Override
    public List<OrderVO> findOrderVOsByUserId(String userId) {
        List<Order> orders = orderMapper.selectList(
                new QueryWrapper<Order>().eq("userid", userId));

        if (orders.isEmpty()) {
            return null;
        }
        List<OrderStatus> statusList = orderStatusMapper.selectList(null);

        List<OrderVO> orderVOList = new ArrayList<>();
        // 将订单和状态合并转换
        for (Order order : orders) {
            OrderVO orderVO = orderToOrderVO(order, statusList);
            if (orderVO.getOrderStatus() != null) {  // 只添加有状态的订单
                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }

    @Override
    public OrderVO enrichOrderWithListPrice(OrderVO orderVO) {
        List<LineItemVO> lineItems = orderVO.getLineItems();
        if (lineItems != null) {
            for (LineItemVO item : lineItems) {
                BigDecimal listPrice = itemMapper.getListPriceByItemId(item.getItemId());
                item.setListPrice(listPrice);
            }
        }
        return orderVO;
    }

    @Override
    public void updateAddressByOrderid(int orderId,
                                       String shipAddress1,
                                       String shipAddress2,
                                       String shipCity,
                                       String shipState,
                                       String shipZip) {
        Order order = orderMapper.selectById(orderId);
        if (order != null) {
            order.setShipAddress1(shipAddress1);
            order.setShipAddress2(shipAddress2);
            order.setShipCity(shipCity);
            order.setShipState(shipState);
            order.setShipZip(shipZip);
            orderMapper.updateById(order);
        } else {
            throw new RuntimeException("订单不存在");
        }
    }
}
